/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.data;

import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.data.utils.PMF;
import com.google.appengine.api.users.User;

/**
 * Utility class for the registration process of Domain Users
 *
 */
public class RegistrationTokenUtils {
	static Logger log = Logger.getLogger("RegistrationTokenUtils");

	public static RegistrationToken getTokenById(String code) {
		RegistrationToken token = null;
		
		if(code==null || code.isEmpty())
			return token;
			
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(RegistrationToken.class);
		query.setUnique(true);
		try {

			query.setFilter("tokenId == Param");
			query.declareParameters("String Param");
			query.setUnique(true);
			token = (RegistrationToken) query.execute(code);
			pm.currentTransaction().commit();
		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}

		return token;

	}

	

	/**
	 * @param openSocialViewerId
	 * @param consumerKey
	 * @return
	 */
	private static RegistrationToken checkTokenExistsByOpenSocial(String openSocialViewerId,
			String consumerKey) {
		RegistrationToken token = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(RegistrationToken.class);
		query.setUnique(true);
		try {

			query.setFilter("openSocialViewerId == openSocialViewrIdParam && consumerKey == consumerKeyParam");
			query.declareParameters("String openSocialViewrIdParam, String consumerKeyParam");
			query.setUnique(true);
			token = (RegistrationToken) query.execute(openSocialViewerId,
					consumerKey);

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}

		return token;

	}
	
	/**
	 * @param user
	 * @return
	 */
	private static RegistrationToken checkTokenExistsByOAuthUser(User user) {
		RegistrationToken token = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(RegistrationToken.class);
		query.setUnique(true);
		try {

			query.setFilter("oauthUserId == oauthUserIdParam && authDomain == authDomainParam");
			query.declareParameters("String oauthUserIdParam, String authDomainParam");
			query.setUnique(true);
			token = (RegistrationToken) query.execute(user.getUserId(),
					user.getAuthDomain());

		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}

		return token;

	}
	
    /**
     * @param tokenId
     * @param user
     * @return
     * @throws Exception
     */
    public static RegistrationToken updateTokenForOauth(String tokenId,User user) throws Exception {

    	RegistrationToken token =null;
    	
    	if(tokenId == null || user == null)
    		return null;
	
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(RegistrationToken.class);
		query.setUnique(true);
		try {
			query.setFilter("tokenId == Param");
			query.declareParameters("String Param");
			query.setUnique(true);
			token = (RegistrationToken) query.execute(tokenId);
			if(token!=null)
			{
				token.setAuthDomain(user.getAuthDomain());
				token.setOauthUserId(user.getUserId());
				token.setEmail(user.getEmail());
				token = pm.makePersistent(token);
			}
			pm.currentTransaction().commit();
			
		} catch (Exception e) {
			throw e;
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}
		return token;

	}
    
    /**
     * @param tokenId
     * @param viewerId
     * @param consumerKey
     * @return
     * @throws Exception
     */
    public static RegistrationToken updateTokenForOpenSocial(String tokenId,String viewerId, String consumerKey) throws Exception {

    	RegistrationToken token =null;
    	
    	if(tokenId == null || viewerId == null || consumerKey == null)
    		return null;
	
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(RegistrationToken.class);
		query.setUnique(true);
		try {
			query.setFilter("tokenId == Param");
			query.declareParameters("String Param");
			query.setUnique(true);
			token = (RegistrationToken) query.execute(tokenId);
			if(token!=null)
			{
				token.setConsumerKey(consumerKey);
				token.setOpenSocialViewerId(viewerId);
				token = pm.makePersistent(token);
			}
			pm.currentTransaction().commit();
			
		} catch (Exception e) {
			throw e;
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}
		return token;

	}
    
	

	/**
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static RegistrationToken createNew(GadgletRequestWrapper request)
			throws Exception {

		RegistrationToken token = checkTokenExistsByOpenSocial(
				request.getOpenSocialViewerId(),
				request.getOpenSocialConsumerKey());
		if (token != null)
			return token;

		token = new RegistrationToken(request.getOpenSocialViewerId(),
				request.getOpenSocialConsumerKey());

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();

		try {
			token = pm.makePersistent(token);
			pm.currentTransaction().commit();
		} catch (Exception e) {
			throw e;
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}
		return token;

	}
	
	/**
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public static RegistrationToken createNew(User user) throws Exception {

		RegistrationToken token = checkTokenExistsByOAuthUser(user);
		if (token != null)
			return token;

		token = new RegistrationToken(user);

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();

		try {
			token = pm.makePersistent(token);
			pm.currentTransaction().commit();
		} catch (Exception e) {
			throw e;
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();

			pm.close();
		}
		return token;

	}

}
